<?php
namespace app\common\model;
use think\Loader;
use think\Db;

class GmTool
{
    public function update($cpsId){
        $data['result']=0;
        $data['msg']='没有当前版本';
        $data['datas']=array('version'=>'0','url'=>'','desc'=>'','updatetime'=>'');
        return $data;
    }

    //获取游戏列表
    public function getGames($page){
        if(empty($page)){
            $page=1;
        }
        $attr=[
            'publish_attr'=>['publish_attr'=>2]
        ];
        $games=Loader::model('GamePublish')->_getGamesByAttr($attr,$page);
        $data=[];
        foreach($games as $v){
            $data[]=[
                'id'=>$v['id'],
                'game_id'=>$v['game_id'],
                'game_name'=>$v['game_name']
            ];
        }
        return $data;
    }

    //获取游戏区服
    public function getServers($myUserId,$gameId){
        $User=new User($myUserId,'id');

        $userGameMap=$User->getUserGameMap($myUserId,1000);
        if(!isset($userGameMap[$gameId]['channel']['channel_id'])){
            Out::exception('没有进入过该游戏');
        }
        $channelId=$userGameMap[$gameId]['channel']['channel_id'];
        $server=[];
        if(!empty($userGameMap[$gameId]['server'])){
            foreach($userGameMap[$gameId]['server'] as $v){
                $server[]=[
                    'server_id'=>$v['server_id'],
                    'server_name'=>$v['server_name']
                ];
            }
        }

        if(empty($server)){
            return err('没有找到区服');
        }else{
            $ret['result'] = 1;
            $ret['msg']='ok';
            $ret['data'] = array(
                'server' => $server,
                'channel_id' => $channelId
            );
            return $ret;
        }
    }

    //获取游戏角色
    public function getRoles($myUserId,$gameId,$serverId){
        $User=new User($myUserId,'id');

        $userGameMap=$User->getUserGameMap($myUserId,1000);
        $role=[];
        if(isset($userGameMap[$gameId]['server'][$serverId]['role'])){
            foreach($userGameMap[$gameId]['server'][$serverId]['role'] as $v){
                $role[]=[
                    'role_id'=>$v['role_id'],
                    'role_name'=>$v['role_name'],
                    'total_charge'=>$v['total_charge']
                ];
            }
        }
        if(empty($role)){
            return err('没有找到区服');
        }else{
            $ret['result'] = 1;
            $ret['msg']='ok';
            $ret['data'] = array(
                'role' => $role,
            );
            return $ret;
        }
    }

    //获取游戏权限列表
    public function getPrivileges($gameId){

        $privilege=Db::name('gm_privilege')
            ->where(['game_id'=>$gameId])
            ->select();

        if(empty($privilege)){
            return err('没有找到相应权限');
        }else{
            $ret['result'] = 1;
            $ret['msg']='ok';
            $ret['data'] = array(
                'privilege' => $privilege
            );
            return $ret;
        }
    }

    //发放道具
    public function getProps($gameId,$privilegeId,$content,$page){

        if($content){
            $name = array('like', "%{$content}%");
        }else{
            $name='1=1';
        }
        $db=Db::name('gm_prop');
        $prop=$db
            //->field('id game_id, name,cp_prop_id,desc,max')
            ->where(['privilege_id'=>$privilegeId])
            ->where($name)
            ->limit(($page-1)*10,10)
            ->order('id asc')
            ->select();
        //Out::exception($db->getLastSql());
        $gmProp=[];
        if($prop){
            foreach($prop as $k=>$v){
                $gmProp[$k]=array(
                    'prop_id'=>$v['id'],
                    'prop_name'=>$v['name'],
                    'icon'=>"http://cdn.miyuhaiwai.com/GmTool/ItemImg/$gameId/{$v['cp_prop_id']}.png",
                    'desc'=>$v['desc'],
                );
            }
        }


        if(empty($gmProp)){
            return err('没有找到任何权限');
        }else{
            $ret['result'] = 1;
            $ret['msg']='ok';
            $ret['data'] = array(
                'prop' => $gmProp,
                //'total' => $total
            );
            return $ret;
        }
    }

    public function apply($myUserId,$gameId,$serverId,$roleId,$privilegeId,$propId,$propNum){


        $User=new User($myUserId,'id');

        $roleArr=$User->getRole($gameId,$serverId,$roleId);
        if($roleArr){
            if($roleArr['total_charge']<=0){
                return err('充值总金额为0');
            }
        }
        $totalAmount=$roleArr['total_charge'];

        $Game=Loader::model(config('game_model'));
        $gameCallback=$Game->getCallback($gameId,$serverId);
        if(empty($gameCallback)){
            return err('游戏回调地址未配置');
        }
        $prop=Db::name('gm_prop')
            ->where(['id'=>$propId])
            ->find();
        if(empty($prop)){
            return err('未找到对应的道具');
        }
        $privilege=Db::name('gm_privilege')
            ->where(['id'=>$privilegeId])
            ->find();
        if(empty($privilege)){
            return err('未找到对应的权限');
        }


        if($totalAmount>=$privilege['amount']){//满足条件,向cp申请道具
            if($propNum>$prop['max']){
                return err('数量超过最大限制');
            }else {
                $params['my_user_id'] = $myUserId;
                $params['server_id']=$serverId;
                $params['role_id']=$roleId;
                $params['total_charge'] = $totalAmount;
                $params['prop_name'] = $prop['name'];
                $params['prop_id'] = $prop['cp_prop_id'];
                $params['prop_num']=$propNum;
                $params['action']="PROPNOTIFY";

                $secret=$Game->get('secret');
                ksort($params);
                $str='';
                foreach($params as $k=>$v){
                    $str.=$k.'='.$v;
                }
                $str.=$secret;
                $params['sign']=md5($str);
                $result='';
                try{
                    $result = Http::post($gameCallback, $params);
                }catch (\Exception $e){
                    return err($e->getMessage());
                }

                if($result){
                    $res=json_decode($result,true);
                    if(is_array($res)){
                        if($res['result']==1){
                            return suc('道具发放成功');
                        }else{
                            return err('返回数据错误:'.$result);
                        }
                    }else{
                        return err('接口返回错误:'.$result);
                    }
                }


                //日志处理
            }
        }else{//不满足条件,返回出错提示
            return err('权限不够,请充值后再试');
        }
    }

}